#!/usr/bin/env python3
import os
import sys

sys.path.append(
    os.path.join(os.path.dirname(os.path.abspath(__file__)),
                 '../../utils/')  # 按实际路径修改
)

import grpc
import p4runtime_lib.bmv2
import p4runtime_lib.helper
from p4runtime_lib.switch import ShutdownAllSwitchConnections
from p4runtime_lib.error_utils import printGrpcError

def install_ipv4_lpm(p4info_helper, switch, dst_ip, dst_mac, out_port):
    table_entry = p4info_helper.buildTableEntry(
        table_name="MyIngress.ipv4_lpm",
        match_fields={"hdr.ipv4.dstAddr": (dst_ip, 32)},
        action_name="MyIngress.ipv4_forward",
        action_params={
            "dstAddr": dst_mac,
            "port": out_port
        }
    )
    switch.WriteTableEntry(table_entry)
    print(f"[{switch.name}] Rule: {dst_ip} -> {dst_mac} via port {out_port}")

def main():
    p4info_path = "build/source_routing.p4.p4info.txt"
    bmv2_json_path = "build/source_routing.json"

    p4info_helper = p4runtime_lib.helper.P4InfoHelper(p4info_path)

    try:
        s1 = p4runtime_lib.bmv2.Bmv2SwitchConnection(
            name='s1', address='127.0.0.1:50051', device_id=0,
            proto_dump_file='logs/s1-src.txt'
        )
        s2 = p4runtime_lib.bmv2.Bmv2SwitchConnection(
            name='s2', address='127.0.0.1:50052', device_id=1,
            proto_dump_file='logs/s2-src.txt'
        )
        s3 = p4runtime_lib.bmv2.Bmv2SwitchConnection(
            name='s3', address='127.0.0.1:50053', device_id=2,
            proto_dump_file='logs/s3-src.txt'
        )

        # 初始化连接与配置 P4 pipeline
        for sw in [s1, s2, s3]:
            sw.MasterArbitrationUpdate()
            sw.SetForwardingPipelineConfig(
                p4info=p4info_helper.p4info,
                bmv2_json_file_path=bmv2_json_path
            )
            print(f"[INFO] Set pipeline config on {sw.name}")

        # ====== 下发 IPv4 转发表项 ======

        # --- s1 ---
        install_ipv4_lpm(p4info_helper, s1, "10.0.1.1", "08:00:00:00:01:11", 1)  # h1
        install_ipv4_lpm(p4info_helper, s1, "10.0.2.2", "08:00:00:00:02:00", 2)  # via s2
        install_ipv4_lpm(p4info_helper, s1, "10.0.3.3", "08:00:00:00:03:00", 3)  # via s3

        # --- s2 ---
        install_ipv4_lpm(p4info_helper, s2, "10.0.2.2", "08:00:00:00:02:22", 1)  # h2
        install_ipv4_lpm(p4info_helper, s2, "10.0.1.1", "08:00:00:00:01:00", 2)  # via s1
        install_ipv4_lpm(p4info_helper, s2, "10.0.3.3", "08:00:00:00:03:00", 3)  # via s3

        # --- s3 ---
        install_ipv4_lpm(p4info_helper, s3, "10.0.3.3", "08:00:00:00:03:33", 1)  # h3
        install_ipv4_lpm(p4info_helper, s3, "10.0.1.1", "08:00:00:00:01:00", 2)  # via s1
        install_ipv4_lpm(p4info_helper, s3, "10.0.2.2", "08:00:00:00:02:00", 3)  # via s2

        print("\n[INFO] All ipv4_lpm rules installed successfully!")

    except grpc.RpcError as e:
        printGrpcError(e)
    finally:
        ShutdownAllSwitchConnections()

if __name__ == '__main__':
    main()
